package routers

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"

	"web/pkg/app"
	"web/pkg/e"
	"web/pkg/util"
	"web/service/auth"
)

type authRequest struct {
	Username string `valid:"Required; MaxSize(50)"`
	Password string `valid:"Required; MaxSize(50)"`
}

// GetAuth 获取认证信息
// @Summary Get Auth
// @Produce  json
// @Param username query string true "userName"
// @Param password query string true "password"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /auth [get]
func GetAuth(c *gin.Context) {
	valid := validation.Validation{}

	username := c.PostForm("username")
	password := c.PostForm("password")

	a := authRequest{Username: username, Password: password}
	ok, _ := valid.Valid(&a)

	if !ok {
		app.MarkErrors(valid.Errors)
		app.Fail(c, e.INVALID_PARAMS, nil)
		return
	}

	authService := auth.Auth{Username: username, Password: password}
	isExist, err := authService.Check()
	if err != nil {
		app.Fail(c, e.ERROR_AUTH_CHECK_TOKEN_FAIL, nil)
		return
	}

	if !isExist {
		app.Fail(c, e.ERROR_AUTH, nil)
		return
	}

	token, err := util.GenerateToken(username, password)
	if err != nil {
		app.Fail(c, e.ERROR_AUTH_TOKEN, nil)
		return
	}

	app.Success(c, map[string]string{
		"token": token,
	})
}
